<?php

namespace App\Api\Controllers;


use App\Api\Requests\MapServiceRequest;

class MapServiceController extends BaseController
{

    public function getAddress(MapServiceRequest $request)
    {
        $longitude = $request->get('longitude');
        $latitude = $request->get('latitude');

        $url = 'http://apis.map.qq.com/ws/geocoder/v1/?location=' . $latitude . ',' . $longitude . '&key=' . env('MAP_KEY');
        $res = json_decode(file_get_contents($url), true);
        $arr = [
            'address' => $res['result']['address'],
        ];
        $address_reference = $res['result']['address_reference'];
        foreach ($address_reference as $k => $v) {
            if (($k != 'business_area') && ($v['title'] != '')) {
                $new_address[] = ['title' => $v['title'], 'lat' => $v['location']['lat'], 'lng' => $v['location']['lng']];
            }
        }
        $arr['address_reference'] = $new_address;
        return $arr;
    }


    public function search(MapServiceRequest $request)
    {
        //$longitude = $request->get('longitude');
        //$latitude = $request->get('latitude');
        $url_city = 'http://apis.map.qq.com/ws/location/v1/ip?key=' . env('MAP_KEY');
        $city_res = collect(json_decode(file_get_contents($url_city),true));
        if($city_res->get('result')){
            $city = $city_res['result']['ad_info']['city'];
        }else{
            return json_encode(['err_msg'=>'未搜索到结果']);
        }
        $keyword = $request->get('keyword');
        $url = 'http://apis.map.qq.com/ws/place/v1/search?';
        $arr = [
            'keyword' => $keyword,
            'key' => env('MAP_KEY'),
            'boundary' => 'region('.$city.',0)'
        ];
        $url .= http_build_query($arr);
        $res = collect(json_decode(file_get_contents($url), true));
        //dd($res->toArray());
        $newArr = array();
        if ($res->get('data')) {
            foreach ($res['data'] as $k => $v) {
                $newArr[] = [
                    'title' => $v['title'],
                    'address' => $v['address'],
                    'longitude' => $v['location']['lng'],
                    'latitude' => $v['location']['lat']
                ];
            }
        }

        return $newArr;
    }
}